package cn.edu.baiyunu.myapplication.ui.screens.add.viewmodel

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.edu.baiyunu.myapplication.data.model.Category
import cn.edu.baiyunu.myapplication.data.model.Transaction
import cn.edu.baiyunu.myapplication.data.repository.CategoryRepository
import cn.edu.baiyunu.myapplication.data.repository.TransactionRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.util.Date
import java.util.UUID
import javax.inject.Inject

/**
 * 添加/编辑交易屏幕UI状态
 */
data class AddEditTransactionUiState(
    val isLoading: Boolean = true,
    val isEditMode: Boolean = false,
    val transactionId: String? = null,
    
    // 交易基本信息
    val transactionType: String = "expense", // expense或income
    val amount: String = "",
    val categoryId: String? = null,
    val selectedDate: Long = System.currentTimeMillis(),
    val note: String = "",
    
    // 分类列表
    val expenseCategories: List<Category> = emptyList(),
    val incomeCategories: List<Category> = emptyList(),
    
    // 错误状态
    val amountError: Boolean = false,
    val categoryError: Boolean = false,
    val generalError: String? = null,
    
    // 保存状态
    val isSaved: Boolean = false
)

/**
 * 添加/编辑交易视图模型
 */
@HiltViewModel
class AddEditTransactionViewModel @Inject constructor(
    private val transactionRepository: TransactionRepository,
    private val categoryRepository: CategoryRepository,
    savedStateHandle: SavedStateHandle
) : ViewModel() {
    
    private val _uiState = MutableStateFlow(AddEditTransactionUiState())
    val uiState: StateFlow<AddEditTransactionUiState> = _uiState.asStateFlow()
    
    init {
        // 检查是否处于编辑模式
        val transactionId = savedStateHandle.get<String>("transactionId")
        
        if (!transactionId.isNullOrEmpty()) {
            // 加载现有交易进行编辑
            _uiState.update { it.copy(isEditMode = true, transactionId = transactionId) }
            loadTransaction(transactionId)
        } else {
            // 加载分类数据
            loadCategories()
        }
    }
    
    /**
     * 加载已有交易进行编辑
     */
    fun loadTransaction(transactionId: String) {
        viewModelScope.launch {
            try {
                transactionRepository.getTransactionById(transactionId).collect { transaction ->
                    if (transaction == null) {
                        _uiState.update { 
                            it.copy(
                                generalError = "找不到该交易记录",
                                isLoading = false
                            )
                        }
                        return@collect
                    }
                    
                    // 更新UI状态
                    _uiState.update { 
                        it.copy(
                            isEditMode = true,
                            transactionId = transactionId,
                            transactionType = transaction.type,
                            amount = transaction.amount.toString(),
                            categoryId = transaction.categoryId,
                            selectedDate = transaction.date,
                            note = transaction.note,
                            isLoading = false
                        )
                    }
                    
                    // 加载分类列表
                    loadCategories()
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(
                        generalError = "加载交易信息失败: ${e.message}",
                        isLoading = false
                    )
                }
            }
        }
    }
    
    /**
     * 加载分类列表
     */
    private fun loadCategories() {
        viewModelScope.launch {
            val expenseFlow = categoryRepository.getExpenseCategories()
            val incomeFlow = categoryRepository.getIncomeCategories()
            
            combine(expenseFlow, incomeFlow) { expenses, incomes ->
                _uiState.update { 
                    it.copy(
                        expenseCategories = expenses,
                        incomeCategories = incomes,
                        isLoading = false
                    )
                }
            }.collect { /* 收集流结果但不需要做额外处理 */ }
        }
    }
    
    /**
     * 设置交易类型
     */
    fun setTransactionType(type: String) {
        if (type != "expense" && type != "income") return
        
        _uiState.update { 
            it.copy(
                transactionType = type,
                // 切换类型时清除选中的分类
                categoryId = null,
                categoryError = false
            )
        }
    }
    
    /**
     * 设置金额
     */
    fun setAmount(amount: String) {
        _uiState.update { 
            it.copy(
                amount = amount,
                amountError = false
            )
        }
    }
    
    /**
     * 设置分类
     */
    fun setCategory(categoryId: String) {
        _uiState.update { 
            it.copy(
                categoryId = categoryId,
                categoryError = false
            )
        }
    }
    
    /**
     * 设置日期
     */
    fun setDate(timestamp: Long) {
        _uiState.update { it.copy(selectedDate = timestamp) }
    }
    
    /**
     * 设置备注
     */
    fun setNote(note: String) {
        _uiState.update { it.copy(note = note) }
    }
    
    /**
     * 验证表单
     */
    private fun validateForm(): Boolean {
        var isValid = true
        
        // 验证金额
        val amount = _uiState.value.amount.toDoubleOrNull()
        if (amount == null || amount <= 0) {
            _uiState.update { it.copy(amountError = true) }
            isValid = false
        }
        
        // 验证分类
        if (_uiState.value.categoryId == null) {
            _uiState.update { it.copy(categoryError = true) }
            isValid = false
        }
        
        return isValid
    }
    
    /**
     * 保存交易
     */
    fun saveTransaction() {
        // 表单验证
        if (!validateForm()) return
        
        viewModelScope.launch {
            try {
                val amount = _uiState.value.amount.toDoubleOrNull() ?: 0.0
                val state = _uiState.value
                
                val transaction = if (state.isEditMode && state.transactionId != null) {
                    // 更新交易
                    Transaction(
                        id = state.transactionId,
                        type = state.transactionType,
                        amount = amount,
                        categoryId = state.categoryId ?: "",
                        date = state.selectedDate,
                        note = state.note
                    )
                } else {
                    // 创建新交易
                    Transaction(
                        id = UUID.randomUUID().toString(),
                        type = state.transactionType,
                        amount = amount,
                        categoryId = state.categoryId ?: "",
                        date = state.selectedDate,
                        note = state.note
                    )
                }
                
                if (state.isEditMode) {
                    transactionRepository.updateTransaction(transaction)
                } else {
                    transactionRepository.addTransaction(transaction)
                }
                
                // 标记保存成功
                _uiState.update { it.copy(isSaved = true) }
                
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(
                        generalError = "保存失败: ${e.message}"
                    )
                }
            }
        }
    }
    
    /**
     * 重置错误状态
     */
    fun resetErrorState() {
        _uiState.update { 
            it.copy(
                amountError = false,
                categoryError = false,
                generalError = null
            )
        }
    }
} 